<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频解析服务 - IP黑名单管理</title>
    <link href="/static/bootstrap5/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">视频解析服务</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"><a class="nav-link" href="/">服务状态</a></li>
                    <li class="nav-item"><a class="nav-link" href="/parse-test">解析测试</a></li>
                    <li class="nav-item"><a class="nav-link" href="/user-manage">用户管理</a></li>
                    <li class="nav-item"><a class="nav-link active" href="/ip-blacklist">IP黑名单</a></li>
                    <li class="nav-item"><a class="nav-link" href="/config-manage">配置管理</a></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item d-none" id="userInfoNav"><span class="nav-link" id="userInfo"></span></li>
                    <li class="nav-item">
                        <button class="btn btn-outline-light btn-sm" id="logoutBtn">退出登录</button>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- IP黑名单管理内容 -->
    <div class="container">
        <div class="row mb-4">
            <div class="col">
                <h4>IP黑名单管理 <span class="text-muted">(仅管理员可见)</span></h4>
            </div>
        </div>

        <!-- 添加IP到黑名单 -->
        <div class="card shadow mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0">添加IP到黑名单</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-success d-none" id="addSuccessAlert" role="alert"></div>
                <div class="alert alert-danger d-none" id="addErrorAlert" role="alert"></div>

                <form id="addBlacklistForm" class="row g-3">
                    <div class="col-md-4">
                        <label for="ipAddress" class="form-label">IP地址 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="ipAddress" placeholder="例如：192.168.1.1" required>
                    </div>
                    <div class="col-md-4">
                        <label for="blockDuration" class="form-label">拉黑时长（小时）</label>
                        <select class="form-select" id="blockDuration">
                            <option value="24">24小时</option>
                            <option value="72">3天</option>
                            <option value="168">7天</option>
                            <option value="0">永久拉黑</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="blockReason" class="form-label">拉黑原因 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="blockReason" placeholder="例如：恶意请求" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary w-100">添加到黑名单</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- IP黑名单列表 -->
        <div class="card shadow">
            <div class="card-header bg-light">
                <h5 class="mb-0">黑名单列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>IP地址</th>
                                <th>拉黑原因</th>
                                <th>拉黑时间</th>
                                <th>过期时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="blacklistTableBody">
                            <!-- JS动态生成黑名单列表 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/bootstrap5/js/bootstrap.bundle.min.js"></script>
    <script>
        // 1. 权限验证（仅管理员可访问）
        async function checkAdminAuth() {
            const token = localStorage.getItem('access_token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            try {
                const response = await fetch('/users/me', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                if (!response.ok) {
                    throw new Error('Token无效');
                }
                
                const user = await response.json();

                if (!user.is_admin) {
                    // 非管理员，跳首页
                    window.location.href = '/';
                } else {
                    // 管理员：显示用户信息和加载黑名单
                    document.getElementById('userInfo').textContent = `当前用户：${user.username}（管理员）`;
                    document.getElementById('userInfoNav').classList.remove('d-none');
                    loadBlacklist(token);
                }
            } catch (err) {
                localStorage.removeItem('access_token');
                window.location.href = '/login';
            }
        }

        // 2. 加载黑名单列表
        async function loadBlacklist(token) {
            const tableBody = document.getElementById('blacklistTableBody');
            tableBody.innerHTML = '<tr><td colspan="5" class="text-center">加载中...</td></tr>';

            try {
                const response = await fetch('/admin/blacklist', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                if (!response.ok) {
                    throw new Error('获取黑名单失败');
                }
                
                const data = await response.json();
                const blacklist = data.data || [];

                if (blacklist.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="5" class="text-center">暂无拉黑IP</td></tr>';
                    return;
                }

                // 渲染黑名单列表
                tableBody.innerHTML = '';
                blacklist.forEach(item => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${item.ip_address}</td>
                        <td>${item.reason}</td>
                        <td>${item.blocked_at}</td>
                        <td>${item.expires_at}</td>
                        <td>
                            <button class="btn btn-sm btn-success" 
                                    onclick="removeFromBlacklist('${item.ip_address}')">
                                解除拉黑
                            </button>
                        </td>
                    `;
                    tableBody.appendChild(tr);
                });
            } catch (err) {
                tableBody.innerHTML = `<tr><td colspan="5" class="text-center text-danger">加载失败: ${err.message}</td></tr>`;
                console.error('加载黑名单失败：', err);
            }
        }

        // 3. 添加IP到黑名单
        document.getElementById('addBlacklistForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const ipAddress = document.getElementById('ipAddress').value;
            const blockDuration = parseInt(document.getElementById('blockDuration').value);
            const blockReason = document.getElementById('blockReason').value;
            const token = localStorage.getItem('access_token');

            const successAlert = document.getElementById('addSuccessAlert');
            const errorAlert = document.getElementById('addErrorAlert');
            successAlert.classList.add('d-none');
            errorAlert.classList.add('d-none');

            // 简单验证IP格式
            const ipRegex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
            if (!ipRegex.test(ipAddress)) {
                errorAlert.textContent = '请输入有效的IP地址';
                errorAlert.classList.remove('d-none');
                return;
            }

            try {
                // 注意：实际项目中需要实现添加黑名单的API
                // 这里使用模拟数据
                await new Promise(resolve => setTimeout(resolve, 500));
                
                successAlert.textContent = `IP ${ipAddress} 已成功添加到黑名单！`;
                successAlert.classList.remove('d-none');
                
                // 重置表单并刷新列表
                document.getElementById('addBlacklistForm').reset();
                loadBlacklist(token);
            } catch (err) {
                errorAlert.textContent = `操作失败：${err.message}`;
                errorAlert.classList.remove('d-none');
            }
        });

        // 4. 从黑名单中移除IP
        async function removeFromBlacklist(ipAddress) {
            const token = localStorage.getItem('access_token');
            if (!confirm(`确定要解除对 ${ipAddress} 的拉黑吗？`)) return;

            try {
                // 注意：实际项目中需要实现解除拉黑的API
                // 这里使用模拟数据
                await new Promise(resolve => setTimeout(resolve, 500));
                
                alert(`IP ${ipAddress} 已成功解除拉黑！`);
                loadBlacklist(token);
            } catch (err) {
                alert(`操作失败：${err.message}`);
            }
        }

        // 5. 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            localStorage.removeItem('access_token');
            window.location.href = '/login';
        });

        // 页面加载时验证权限
        checkAdminAuth();
    </script>
</body>
</html>
    